package com.dongly.sort;

import java.util.Arrays;
import java.util.Objects;

/**
 * 插入排序
 */
public class InsertSort {

    public static void main(String[] args) {
        int[] array = {5, 2, 3, 3, 1, 8, 4, 6};
        // sort1(array);
        sort2(array);
        System.out.println(Arrays.toString(array));
    }

    public static void sort2(int[] array) {
        int temp;
        int length = array.length;
        for (int i = 1; i < length; i++) {
            for (int j = i; j > 0; j--) {
                if (array[j] < array[j - 1]) {
                    temp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = temp;
                }
            }
        }

    }


    public static void sort1(int[] array) {
        Objects.requireNonNull(array);
        int i, j, target, temp;
        int length = array.length;
        // 假定第一个元素被放到了正确的位置上
        // 这样只需要遍历[1, length - 1]
        for (i = 1; i < length; i++) {
            j = i;
            target = array[i];

            while (j > 0 && target < (temp = array[j - 1])) {
                array[j] = temp;
                j--;
            }
            array[j] = target;
        }
    }
}
